package com.fyzk.activity.forum;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;

import com.alibaba.fastjson.JSON;
import com.fyzk.activity.app.ActivityTaskManager;
import com.fyzk.base.BaseActivity;
import com.fyzk.activity.user.LoginActivity;
import com.fyzk.activity.user.NetProgressView;
import com.fyzk.data.AppLotteryInfos;
import com.fyzk.data.preference.MySharedPreferences;
import com.fyzk.view.ViewCallBack;
import com.tyjc.lottery.R;
import com.fyzk.net.Commands;
import com.fyzk.utils.LogUtil;
import com.fyzk.view.RefreshListView;
import com.fyzk.view.TopTitleView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.http.body.RequestBody;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import http.Common.CommandUtil;
import com.wf.domain.UrlDef;
import http.StringResultBean;

/**
 * Created by fanxs11 on 17/5/8.
 *
 * 帖子列表
 */

@ContentView(R.layout.ac_topiclist)
public class TopicListActivity extends BaseActivity implements RefreshListView.OnRefreshListener{

    private int topic_id = 0;
    private String title = "";

    @ViewInject(R.id.topiclist_topview)
    private TopTitleView topView;

    @ViewInject(R.id.topiclist_listview)
    private RefreshListView listView;
    private TopicListAdapter adapter;
    private List<TopicListBean> infos = new ArrayList<>();
    private boolean requestType = false;    //请求方式：true加载更多，false首次请求或刷新
    private int page = 1;
    private int count = 10;
    @ViewInject(R.id.topiclist_recordProgressView)
    private NetProgressView recordProgressView;

    @ViewInject(R.id.topiclist_publish)
    private Button publish_btn;     // 发帖



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        topic_id = getIntent().getIntExtra("topic_id", 0);
        title = getIntent().getStringExtra("title");

        initView();
//        getTopicList(topic_id,true);
    }

    @Override
    protected void onResume() {
        super.onResume();
        page = 1;
        getTopicList(topic_id, true);
    }

    private void initView() {
        topView.setOnTitleClickListener(this);
        topView.setCenterText(title);

        publish_btn.setOnClickListener(this);

        listView.setItemsCanFocus(false);
        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        listView.setOnRefreshListener(this);
        adapter = new TopicListAdapter(this, infos);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (listView.isDownPull){
                    return;
                }
                if (i > 0 && i <= infos.size()) {
                    Intent intent = new Intent(getContext(), TopicDetailActivity.class);
                    intent.putExtra("id", infos.get(i - 1).getQuestion_id());
                    startActivity(intent);
                }

            }
        });
    }

    /**
     *  获取帖子列表（论坛）
     */
    private void getTopicList(int topic_id, boolean showProgress) {
        try {
            JSONObject request_json = new JSONObject();
            request_json.put("token", MySharedPreferences.getInstance().getAuthtoken());
            request_json.put("time", System.currentTimeMillis());
            JSONObject data = new JSONObject();
            data.put("post_type", "question");
            data.put("page", page);
            data.put("per_page", count);
            data.put("sort_type", "");
            data.put("topic_id", topic_id);
            request_json.put("data", data);
            LogUtil.d("联网请求json:"+request_json.toString());
            RequestParams params = new RequestParams(UrlDef.FORUM_URL + Commands.FORUM_POSTLIST);

            params.setBodyContent("req="+ URLEncoder.encode(request_json.toString(), "UTF-8"));
            RequestBody body = params.getRequestBody();
            body.setContentType("application/x-www-form-urlencoded");
            params.setRequestBody(body);

            sendRequest(HttpMethod.POST, CommandUtil.FORUM_POSTLIST, params, showProgress);
        } catch (JSONException e) {

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        switch (requestCode) {
            case CommandUtil.FORUM_POSTLIST:
                List<TopicListBean> beans = JSON.parseArray(resultBean.getData(), TopicListBean.class);
                if (requestType) {  // 加载更多
                    if (beans.size() > 0) {
                        infos.addAll(beans);
                        listView.hideFooterView();
                    } else {
                        listView.noMore();
                    }
                } else {
                    infos = beans;
                    listView.hideHeaderView();
                    if (infos.size() == 0) {
                        listView.noMore();
                    }
                }
                adapter.setInfos(infos);
                requestType = false;
                break;
        }
    }

    @Override
    protected void onFailure(int requestCode) {
        super.onFailure(requestCode);
        if (!requestType) { // 下拉刷新或第一次请求
            infos.clear();

        } else {    // 加载更多
            listView.noMore();

        }
        adapter.setInfos(infos);
    }

    @Override
    public void onClick(View arg0) {
        super.onClick(arg0);
        switch (arg0.getId()) {
            case R.id.topiclist_publish:
                if (!MySharedPreferences.getInstance().getLoginStatus()) {
                    AppLotteryInfos.clear();
                    ViewCallBack.getInstance().countDownObjs.clear();
                    ActivityTaskManager.getInstance().closeAllActivity();
                    Intent intent = new Intent(getContext(), LoginActivity.class);
                    startActivity(intent);
                    return;
                }
                Intent intent = new Intent(getContext(), PostingActivity.class);
                intent.putExtra("title", title);
                startActivity(intent);
                break;
            default:

                break;
        }
    }

    @Override
    public void onDownPullRefresh() {
        page = 1;
        requestType = false;
        getTopicList(topic_id,true);
    }

    @Override
    public void onLoadingMore() {
        requestType = true;
        page++;
        getTopicList(topic_id,false);
    }
}
